package com.aryankh.controller;

import com.aryankh.constant.Constants;
import com.aryankh.core.RedisTemplate;
import com.aryankh.entity.KhLoginUser;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Set;

/**
 * @version 1.0
 * @Author AryanKH
 * @Date 2022/6/2 12:48
 * @Default
 */
public class BaseController {
    @Resource
    RedisTemplate redisTemplate;
    protected KhLoginUser getLoginUser() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        //获取首部信息的token
        String token = request.getHeader(Constants.AUTHORIZATION);
        // String tokenKey=Constants.TOKEN_PREFIX+request.getHeader("username")+":"+token;
        //先判断有无Authorization 拿到首部信息 Authorization 的值
        if (token == null) {
            throw new RuntimeException("当前用户未登录");
        }
        Set<String> keys = redisTemplate.keys(Constants.TOKEN_PREFIX + "*" + token);
        if (keys == null || keys.size() == 0) {
            throw new RuntimeException("当前用户未登录");
        }
        String tokenKey = (String) keys.toArray()[0];
        //使用token去redis中查看有无对应的loginUser
        return redisTemplate.getObject(tokenKey, new TypeReference<KhLoginUser>() {
        });
    }
}
